package com.jwsoft.manager.core.integration.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.core.helper.DictHelper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.SchoolNatureEnum;
import com.jwsoft.manager.common.vo.eduClassSetting.*;
import com.jwsoft.manager.common.vo.eduSchool.EduSchoolVO;
import com.jwsoft.manager.core.dao.service.EduSchoolService;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import cn.hutool.core.convert.Convert;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.bifang.engine.assistant.core.exception.AppException;
import org.springframework.util.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.jwsoft.manager.core.integration.EduClassSettingIntegration;
import com.jwsoft.manager.core.dao.service.EduClassSettingService;
import com.jwsoft.manager.core.dao.model.EduClassSetting;

/**
 * 分班设置管理业务实现类
 *
 * @author chenzh
 * @since 2023-08-21
 */
@ApiService(funcCode = "eduClassSetting", title = "分班设置管理")
public class EduClassSettingIntegrationImpl implements EduClassSettingIntegration {

    @Autowired
    public EduClassSettingService eduClassSettingService;
    @Autowired
    private EduHelper eduHelper;
    @Autowired
    private EduSchoolService eduSchoolService;
    @Autowired
    private DictHelper dictHelper;

    @Override
    @OpApi(funcCode = "eduClassSetting0001", title = "分班设置管理分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduClassSettingVO> getList(EduClassSettingQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        if (vo.getYear() == null) {
            vo.setYear(eduHelper.thisYear());
        }
        if (StringUtils.isBlank(vo.getAreaCode())) {
            vo.setAreaCode(SessionUtil.getAreaCode());
        }
        QueryWrapper<EduClassSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(vo.getYear() != null, EduClassSetting::getYear, vo.getYear())
                .eq(StringUtils.isNotBlank(vo.getAreaCode()), EduClassSetting::getAreaCode, vo.getAreaCode())
                .eq(StringUtils.isNotBlank(vo.getSchoolId()), EduClassSetting::getSchoolId, vo.getSchoolId())
                .eq(StringUtils.isNotBlank(vo.getConfigTypeName()), EduClassSetting::getConfigTypeName, vo.getConfigTypeName())
                .eq(StringUtils.isNotBlank(vo.getEnabled()), EduClassSetting::getEnabled, vo.getEnabled());
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<EduClassSetting> list = eduClassSettingService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduClassSetting> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduClassSettingVO> resultList = Convert.toList(EduClassSettingVO.class, pageInfo.getList());
        for (EduClassSettingVO eduClassSettingVO : resultList) {
            if (StringUtils.isNotBlank(eduClassSettingVO.getSchoolId())) {
                EduSchoolVO eduSchoolVO = eduSchoolService.getDetail(eduClassSettingVO.getSchoolId());
                if (eduSchoolVO != null) {
                    eduClassSettingVO.setSchoolName(eduSchoolVO.getSchoolName());
                    eduClassSettingVO.setShortName(eduSchoolVO.getShortName());
                }
            }
        }
        // 转义数据字典值
        // dictHelper.valueToName(resultList, Arrays.asList(DemoDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduClassSetting0002", title = "分班设置管理根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduClassSettingVO getById(EduClassSettingKeyVO vo) {
        EduClassSetting entity = eduClassSettingService.getById(vo.getClassParamId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduClassSettingVO result = Convert.convert(EduClassSettingVO.class, entity);
        if (StringUtils.isNotBlank(result.getSchoolId())) {
            EduSchoolVO eduSchoolVO = eduSchoolService.getDetail(result.getSchoolId());

            if (eduSchoolVO != null) {
                result.setSchoolName(eduSchoolVO.getSchoolName());
                result.setShortName(eduSchoolVO.getShortName());
            }
        }
        String classParams = result.getClassParams();
        if (StringUtils.isNotBlank(classParams)) {
            List<String> codeList = Arrays.stream(classParams.split(",")).map(s -> s).collect(Collectors.toList());
            List<EduClassSettingParamsVO> paramsList = new ArrayList<>();
            for (String code : codeList) {
                EduClassSettingParamsVO paramsVO = new EduClassSettingParamsVO();
                paramsVO.setClassParamCode(code);
                paramsVO.setClassParamTitle(dictHelper.getValue("CLASSPARAMCODE", code));
                paramsList.add(paramsVO);
            }
            result.setParamsVOList(paramsList);
        }
        return result;
    }

    /**
     * 保存前统一校验
     */
    @Override
    @OpApi(funcCode = "eduClassSetting0003", title = "分班设置管理保存前校验", funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduClassSettingVO vo) {
        //主键为空为新增校验
        if (StringUtils.isBlank(vo.getSchoolId())) {
            vo.setSchoolId(SessionUtil.getOrgId());
        }
        if (vo.getClassNum() == null || vo.getClassNum() <= 0) {
            throw new AppException("班级数不能为空或者小于1");
        }
        EduSchoolVO eduSchoolVO = eduSchoolService.getDetail(vo.getSchoolId());
        if (eduSchoolVO != null) {
            vo.setAreaCode(eduSchoolVO.getAreaCode());
        } else {
            throw new AppException("学校id不能为空");
        }
        if (!SchoolNatureEnum.gb.getType().equalsIgnoreCase(eduSchoolVO.getSchoolNature())) {
            if (StringUtils.isBlank(vo.getConfigTypeName())) {
                throw new AppException("招生类别不能为空");
            }
        } else {
            vo.setConfigTypeName(null);
        }
        if (vo.getClassParamId() == null) {
            vo.setYear(eduHelper.thisYear());
        } else {
            if (vo.getYear() - eduHelper.thisYear() != 0) {
                throw new AppException("只能修改当前年度数据");
            }
        }
        //主键不为空为修改校验
        QueryWrapper<EduClassSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduClassSetting::getYear, vo.getYear())
                .eq(EduClassSetting::getSchoolId, vo.getSchoolId())
                .eq(StringUtils.isNotBlank(vo.getConfigTypeName()), EduClassSetting::getConfigTypeName, vo.getConfigTypeName())
                .ne(vo.getClassParamId() != null, EduClassSetting::getClassParamId, vo.getClassParamId());
        if (eduClassSettingService.count(queryWrapper) > 0) {
            throw new AppException("本年度，设置数据已存在");
        }
        if (CollectionUtils.isEmpty(vo.getParamsVOList())) {
            throw new AppException("规则不能为空");
        } else {
            for (EduClassSettingParamsVO paramsVO : vo.getParamsVOList()) {
                int i = 0;
                for (EduClassSettingParamsVO paramsVO2 : vo.getParamsVOList()) {
                    if (paramsVO.getClassParamCode().equalsIgnoreCase(paramsVO2.getClassParamCode())) {
                        i = i + 1;
                    }
                }
                if (i > 1) {
                    throw new AppException("规则不能设置重复");
                }
            }

        }
    }

    @Override
    @OpApi(funcCode = "eduClassSetting0004", title = "分班设置管理新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduClassSetting0004",
            operationName = "分班设置管理新增",
            dataType = "classParamId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduClassSettingVO add(EduClassSettingVO vo) {
        //保存前校验
        checkSave(vo);
        //保存数据
        EduClassSetting entity = Convert.convert(EduClassSetting.class, vo);
        if (StringUtils.isBlank(vo.getEnabled())) {
            entity.setEnabled(BoolEnum.TRUE.getType());
        }
        if (!CollectionUtils.isEmpty(vo.getParamsVOList())) {
            String params = vo.getParamsVOList().stream().map(EduClassSettingParamsVO::getClassParamCode).collect(Collectors.joining(","));
            entity.setClassParams(params);
        }
        eduClassSettingService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setClassParamId(entity.getClassParamId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduClassSetting0005", title = "分班设置管理修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduClassSetting0005",
            operationName = "分班设置管理修改",
            dataType = "classParamId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduClassSettingVO edit(EduClassSettingVO vo) {
        if (ObjectUtils.isEmpty(vo.getClassParamId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduClassSetting oldEntity = eduClassSettingService.getById(vo.getClassParamId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduClassSetting entity = Convert.convert(EduClassSetting.class, vo);
        if (StringUtils.isBlank(vo.getEnabled())) {
            entity.setEnabled(BoolEnum.TRUE.getType());
        }
        if (!CollectionUtils.isEmpty(vo.getParamsVOList())) {
            String params = vo.getParamsVOList().stream().map(EduClassSettingParamsVO::getClassParamCode).collect(Collectors.joining(","));
            entity.setClassParams(params);
        }
        eduClassSettingService.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduClassSetting0006", title = "分班设置管理根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduClassSetting0006",
            operationName = "分班设置管理删除",
            dataType = "classParamId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduClassSettingKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getClassParamId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduClassSetting entity = eduClassSettingService.getById(vo.getClassParamId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduClassSettingService.removeById(vo.getClassParamId());
    }

    @Override
    @OpApi(funcCode = "eduClassSetting0007", title = "分班设置根据年份和学校id查询信息", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    public EduClassSettingVO getByYearAndSchoolId(EduClassSettingYearQueryVO vo) {
        if (vo.getYear() == null) {
            vo.setYear(eduHelper.thisYear());
        }
        if (StringUtils.isBlank(vo.getSchoolId())) {
            throw new AppException("学校id不能为空");
        }
        EduSchoolVO eduSchoolVO = eduSchoolService.getDetail(vo.getSchoolId());
        if (eduSchoolVO == null) {
            throw new AppException("学校基础信息不存在");
        }
        if (!SchoolNatureEnum.gb.getType().equalsIgnoreCase(eduSchoolVO.getSchoolNature())) {
            if (StringUtils.isBlank(vo.getConfigTypeName())) {
                throw new AppException("招生类别不能为空");
            }
        } else {
            vo.setConfigTypeName(null);
        }
        QueryWrapper<EduClassSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduClassSetting::getYear, vo.getYear())
                .eq(EduClassSetting::getSchoolId, vo.getSchoolId())
                .eq(StringUtils.isNotBlank(vo.getConfigTypeName()), EduClassSetting::getConfigTypeName, vo.getConfigTypeName());
        EduClassSetting entity = eduClassSettingService.getOne(queryWrapper, false);
        if (entity == null) {
            return null;
        }
        EduClassSettingVO result = Convert.convert(EduClassSettingVO.class, entity);
        if (StringUtils.isNotBlank(result.getSchoolId())) {


            if (eduSchoolVO != null) {
                result.setSchoolName(eduSchoolVO.getSchoolName());
                result.setShortName(eduSchoolVO.getShortName());
            }
        }
        String classParams = result.getClassParams();
        if (StringUtils.isNotBlank(classParams)) {
            List<String> codeList = Arrays.stream(classParams.split(",")).map(s -> s).collect(Collectors.toList());
            List<EduClassSettingParamsVO> paramsList = new ArrayList<>();
            for (String code : codeList) {
                EduClassSettingParamsVO paramsVO = new EduClassSettingParamsVO();
                paramsVO.setClassParamCode(code);
                paramsVO.setClassParamTitle(dictHelper.getValue("CLASSPARAMCODE", code));
                paramsList.add(paramsVO);
            }
            result.setParamsVOList(paramsList);
        }
        return result;
    }
}
